﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Text;
using Microsoft.SharePoint;
using System.Diagnostics;

namespace CssLinkCustom
{
    public class CssLink : Microsoft.SharePoint.WebControls.CssLink
    {
        Microsoft.SharePoint.WebControls.CssLink myCssLink = new Microsoft.SharePoint.WebControls.CssLink();

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
        }

        protected override void CreateChildControls()
        {
            try
            {
                myCssLink.DefaultUrl = this.DefaultUrl;
                myCssLink.Alternate = this.Alternate;
                myCssLink.EnableTheming = this.EnableTheming;
                myCssLink.EnableViewState = this.EnableViewState;
                myCssLink.ID = this.ID;
                myCssLink.InDesign = this.InDesign;
                myCssLink.SkinID = this.SkinID;
                myCssLink.TemplateControl = this.TemplateControl;
                myCssLink.UIVersion = this.UIVersion;
                myCssLink.Version = this.Version;

                Debug.WriteLine("default url createChildControls: " +myCssLink.DefaultUrl);

                this.Controls.Add(myCssLink);

            }
            catch (Exception ex)
            {
                Debug.WriteLine("CustomCssLink CreateChildControls-error: "+ ex.Message);
            }

        }

        protected override void Render(System.Web.UI.HtmlTextWriter output)
        {

            System.IO.StringWriter myStrWriter = new System.IO.StringWriter();
            HtmlTextWriter myWriter = new HtmlTextWriter(myStrWriter);
            myCssLink.RenderControl(myWriter);

            try
            {
                if (Convert.ToBoolean(myCssLink.Alternate))
                {
                    Debug.WriteLine("myCssLink Alternate : " + "true");

                }
                else
                {
                    Debug.WriteLine("myCssLink Alternate : " + "false");
                }
                Debug.WriteLine("myCssLink DefaultUrl : " + myCssLink.DefaultUrl);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("myCssLink error : " + ex.Message);
            }

            string myLinks = myStrWriter.ToString();
            string[] myLinksTable = myLinks.Split(new char[] { '<' });
            string myNewLinks = "";
            for (int i = 1; i < myLinksTable.Length; i++)
            {
                Debug.WriteLine("Link " + i + "   " + myLinksTable[i]);
                if (!myLinksTable[i].Contains("/_layouts/1033/styles/Themable/corev4.css"))
                {
                    myNewLinks += "\n<" + myLinksTable[i];
                }
            }

            output.Write(myNewLinks);

        }
    }
}
